package com.mf.morefun.service;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Environment;

import com.mf.morefun.MoreFunApplication;
import com.mf.morefun.bean.EventMessageBean;
import com.mf.morefun.bean.GrindingEarsBean;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FilenameFilter;
import java.util.List;

public class HomeworkService {
    private static final File PATH = Environment.getExternalStorageDirectory();// 获取SD卡总目录。
    public List<GrindingEarsBean> musicList;
    public MediaPlayer player; // 定义多媒体对象
    public int songNum; // 当前播放的歌曲在List中的下标,flag为标致
    public String songName; // 当前播放的歌曲名
    private Context mContext;
    //写一个线程来加载网络音乐
    private Thread mThread = null;


    class MusicFilter implements FilenameFilter {
        public boolean accept(File dir, String name) {
            return (name.endsWith(".mp3"));//返回当前目录所有以.mp3结尾的文件
        }
    }

    public HomeworkService(List<GrindingEarsBean> musicList, Context mContext) {
        super();
        player = new MediaPlayer();
        this.musicList = musicList;
        this.mContext = mContext;
    }

    public void setPlayName(String dataSource) {
        File file = new File(dataSource);//假设为D:\\mm.mp3
        String name = file.getName();//name=mm.mp3
        int index = name.lastIndexOf(".");//找到最后一个.
        songName = name.substring(0, index);//截取为mm
    }

    public void play() {
        if (null != mThread && mThread.isAlive()){
            stop();
            mThread.interrupt();
            mThread = null;
        }
        playThread();
    }

    private void playThread(){
        mThread = new Thread(new Runnable() {
            @Override
            public void run() {
                playMusic();
            }
        });
        mThread.start();
    }

    private void playMusic(){
        try {
            if (null == player){
                player = new MediaPlayer();
            }
            player.reset(); //重置多媒体
            String dataSource = musicList.get(songNum).getMfAudio().getAddress();//得到当前播放音乐的路径
            setPlayName(dataSource);//截取歌名
            // 指定参数为音频文件
            player.setAudioStreamType(AudioManager.STREAM_MUSIC);
            player.setDataSource(mContext, Uri.parse(dataSource));//为多媒体对象设置播放路径
//            player.prepare();//准备播放
            player.prepareAsync();
            //setOnCompletionListener 当当前多媒体对象播放完成时发生的事件
            player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                public void onCompletion(MediaPlayer arg0) {
                    EventMessageBean eventMessageBean = new EventMessageBean();
                    eventMessageBean.setNum(0);
                    eventMessageBean.setType(0);
                    eventMessageBean.setProgress(0);
                    EventBus.getDefault().post(eventMessageBean);
                }
            });
            player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    MoreFunApplication.isOut = false;
                    player.start();//开始播放
                    EventMessageBean eventMessageBean = new EventMessageBean();
                    eventMessageBean.setNum(mp.getDuration());
                    eventMessageBean.setType(2);
                    eventMessageBean.setProgress(0);
                    EventBus.getDefault().post(eventMessageBean);
                }
            });
            player.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    MoreFunApplication.isOut = true;
                    EventMessageBean eventMessageBean = new EventMessageBean();
                    eventMessageBean.setNum(0);
                    eventMessageBean.setType(1);
                    eventMessageBean.setProgress(0);
                    EventBus.getDefault().post(eventMessageBean);
                    return true;
                }
            });
        } catch (Exception e) {
            MoreFunApplication.isOut = true;
            EventMessageBean eventMessageBean = new EventMessageBean();
            eventMessageBean.setNum(0);
            eventMessageBean.setType(1);
            eventMessageBean.setProgress(0);
            EventBus.getDefault().post(eventMessageBean);
        }
    }

    //继续播放
    public  void goPlay(){
        int position = getCurrentProgress();
        player.seekTo(position);//设置当前MediaPlayer的播放位置，单位是毫秒。
        try {
            player.prepare();//  同步的方式装载流媒体文件。
        } catch (Exception e) {
            e.printStackTrace();
        }
        player.start();
    }
    // 获取当前进度
    public int getCurrentProgress() {
        if (player != null & player.isPlaying()) {
            return player.getCurrentPosition();
        } else if (player != null & (!player.isPlaying())) {
            return player.getCurrentPosition();
        }
        return 0;
    }

    public void next() {
        songNum = songNum == musicList.size() - 1 ? 0 : songNum + 1;
        play();
    }

    public void last() {
        songNum = songNum == 0 ? musicList.size() - 1 : songNum - 1;
        play();
    }
    // 暂停播放
    public void pause() {
        if (player != null && player.isPlaying()){
            player.pause();
        }
    }

    public void stop() {
        if (player != null && player.isPlaying()) {
            player.stop();
            try {
                mThread.sleep(350);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            player.reset();
            player.release();
            player=null;
        }
    }
}
